package File;

import java.io.*;
import java.util.Scanner;

//查找文件内容和文件名是否包含用户指定的关键字
public class Demo1 {
    public static void main(String[] args) throws IOException {
        System.out.println("请输入你要查找的目录：");
        Scanner scan = new Scanner(System.in);
        String findDirectory = scan.nextLine();
        File file = new File(findDirectory);
        if(!file.isDirectory()) {
            System.out.println("输入的不是目录或者该目录不存在...");
            return;
        }
        System.out.println("请输入你要查找的关键字：");
        String key = scan.nextLine();
        scanDir(file, key);
    }

    private static void scanDir(File rootFile, String key) throws IOException {
        File[] files = rootFile.listFiles();
        for(File file : files) {
            if(file.isDirectory()) {
                scanDir(file, key);
            } else {
                check(file, key);
            }
        }
    }

    private static void check(File file, String key) throws IOException {
        if(file.getName().contains(key)) {
            System.out.println("文件名包含该关键字：" + file.getAbsolutePath());
            return;
        }
        InputStream inputStream = new FileInputStream(file);
        StringBuilder str = new StringBuilder();
        byte[] bytes = new byte[4096];
        while(true) {
            int n = inputStream.read(bytes,0,4096);
            if(n == -1) {
                break;
            }
            str.append(bytes);
        }
    }
}
